/**
 * Express configuration
 */

'use strict';

var express = require('express');
var favicon = require('serve-favicon');
var morgan = require('morgan');
var compression = require('compression');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var cookieParser = require('cookie-parser');
var errorHandler = require('errorhandler');
var path = require('path');
var _ = require('lodash');
var util = require('util');
var config = require('./environment');
var session = require('express-session');
var mongoStore = require('connect-mongo')(session);
var mongoose = require('mongoose');
var sessionStore = new mongoStore({mongooseConnection: mongoose.connection});

module.exports = function (app) {
    //
    app.set("sessionStore", sessionStore);

    // Get current server environment
    var env = app.get('env');

    // Remove x-powered-by header
    app.disable('x-powered-by');

    app.set('views', config.root + '/server/views');
    // Setup view engine for server side templating
    app.engine('.html', require('ejs').__express);
    app.set('view engine', 'html');
    /*app.engine('html', require('ejs').renderFile);
     app.set('view engine', 'html');*/
    app.use(compression());
    app.use(bodyParser.urlencoded({extended: true}));
    app.use(bodyParser.json());
    app.use(methodOverride());
    app.use(cookieParser());

    // Persist sessions with mongoStore
    app.use(session({
        secret: config.secrets.sessionSecret,
        key: config.secrets.sessionKey,
        resave: true,
        saveUninitialized: true,
        store: sessionStore,
        cookie: {maxAge: config.cookie.maxAge}
    }));
    app.use(function (req, res, next) {
        function send(data) {
            res.type('application/json; charset=utf-8').jsonp(data);
        }

        function getData(args) {
            var data = {};
            if (args) {
                args = JSON.parse(util.format('%j', args));
                for (var i in args) {
                    if (args.hasOwnProperty(i)) {
                        _.assign(data, args[i]);
                    }
                }
            }
            return data;
        }

        //
        _.assign(res, {
            createSuccess: function () {
                send(_.assign({success: true}, {data: getData(_.values(arguments))}));
            },
            createFailure: function () {
                send(_.assign({success: false}, getData(_.values(arguments))));
            },
            createResult: function (err, result) {
                err ? res.createFailure(err) : res.createSuccess(result || {});
            }
        });

        //
        next();
    });

    if ('production' === env) {
        app.use(favicon(path.join(config.root, 'client', 'favicon.ico')));
        app.use(express.static(path.join(config.root, 'client')));
        app.set('appPath', config.root + '/client');
        app.use(morgan('dev'));
    }

    if ('development' === env) {
        app.use(require('connect-livereload')());
        app.use(express.static(path.join(config.root, '.tmp')));
        app.use(express.static(path.join(config.root, 'client')));
        app.set('appPath', config.root + '/client');
        app.use(morgan('dev'));
        // Error handler - has to be last
        app.use(errorHandler());
    }
};
